package cn.sdhuijin.mediaplatform;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author sunp@sdhuijin.cn:
 * @version 创建时间：2015年4月9日 下午3:23:17 类说明
 */
public class InstallActivity extends Activity {

	private Button btn_download;
	private Button btn_back;
	private TextView tv_connect;
	private final Timer timer = new Timer();
	private TimerTask task;
	private ProgressDialog progressDialog = null;
	private boolean isConnected = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_install);

		btn_back = (Button) findViewById(R.id.btn_back);
		btn_back.setOnClickListener(listener);

		btn_download = (Button) findViewById(R.id.btn_install);
		btn_download.setOnClickListener(listener);

		tv_connect = (TextView) findViewById(R.id.tv_connect);

		task = new TimerTask() {
			@Override
			public void run() {
				searchDevices();
			}
		};
		timer.schedule(task, 2000, 2000);
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// 已连接
			case 1:
				tv_connect.setTextColor(Color.parseColor("#FF0000"));
				tv_connect.setText(R.string.txt_connect);
				isConnected = true;
				break;
			// 未连接
			case 2:
				tv_connect.setTextColor(Color.parseColor("#CFB53B"));
				tv_connect.setText(R.string.txt_disconnect);
				isConnected = false;
				break;
			// 安装失败
			case 3:
				Toast.makeText(InstallActivity.this,
						R.string.toast_install_fail, Toast.LENGTH_LONG).show();
				progressDialog.dismiss();
				break;
			// 安装成功
			case 4:
				Toast.makeText(InstallActivity.this,
						R.string.toast_install_success, Toast.LENGTH_LONG)
						.show();
				progressDialog.dismiss();
				break;
			case 5:
				progressDialog.dismiss();
				break;
			// 开始安装
			case 6:
				progressDialog = ProgressDialog.show(InstallActivity.this,
						"请稍等...", "正在安装应用到您的手机中...", true);
				progressDialog.setCancelable(true);
				break;
			default:
				break;
			}
		}
	};

	public void searchDevices() {
		BufferedWriter outputStream = null;
		Process process = null;
		Message message = new Message();
		try {
			process = Runtime.getRuntime().exec("su");
			outputStream = new BufferedWriter(new OutputStreamWriter(
					process.getOutputStream()));
			outputStream.write("export ANDROID_ADB_SERVER_PORT=5038" + "\n");
			outputStream.write("adb start-server" + "\n");
			outputStream.write("adb devices" + "\n");
			outputStream.write("exit\n");
			outputStream.flush();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					process.getInputStream(), "gbk"));
			String line = null;
			int num = 0;
			boolean flag = false;
			while ((line = reader.readLine()) != null) {
				num++;
				if (num == 2 && line.contains("device")) {
					flag = true;
				}
			}
			int i = process.waitFor();
			if (flag && i == 0) {
				message.what = 1;
			} else {
				message.what = 2;
			}
		} catch (Exception e) {
			e.printStackTrace();
			message.what = 2;
		} finally {
			try {
				if (outputStream != null) {
					outputStream.close();
				}
				process.destroy();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		handler.sendMessage(message);
	}

	private OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			int id = (Integer) v.getId();
			switch (id) {
			case R.id.btn_install:
				if (isConnected) {
					new Thread(new Runnable() {
						public void run() {
							installApk();
						}
					}).start();
				} else {
					Toast.makeText(InstallActivity.this,
							R.string.txt_toast_disconnect, Toast.LENGTH_LONG)
							.show();
				}
				break;
			case R.id.btn_back:
				finish();
			default:
				break;
			}
		}
	};

	public void installApk() {
		Message messageStart = new Message();
		Message messageEnd = new Message();
		messageStart.what = 6;
		handler.sendMessage(messageStart);
		BufferedWriter outputStream = null;
		Process process = null;
		BufferedWriter outputStreamResult = null;
		Process processResult = null;
		try {
			process = Runtime.getRuntime().exec("su");
			outputStream = new BufferedWriter(new OutputStreamWriter(
					process.getOutputStream()));
			outputStream.write("export ANDROID_ADB_SERVER_PORT=5038" + "\n");
			outputStream
					.write("adb install -r /sdcard/Download/Android1.1.2.apk"
							+ "\n");
			outputStream.write("exit\n");
			outputStream.flush();
			int i = process.waitFor();
			if (i == 0) {
				processResult = Runtime.getRuntime().exec("su");
				outputStreamResult = new BufferedWriter(new OutputStreamWriter(
						processResult.getOutputStream()));
				outputStreamResult.write("export ANDROID_ADB_SERVER_PORT=5038"
						+ "\n");
				outputStreamResult.write("adb shell pm list packages" + "\n");
				outputStreamResult.write("exit\n");
				outputStreamResult.flush();
				int iResult = processResult.waitFor();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(processResult.getInputStream(),
								"gbk"));
				String line = null;
				int num = 0;
				while ((line = reader.readLine()) != null) {
					if (line.equals("package:com.android.clock.sd")) {
						num = num + 1;
					}
				}
				if (num > 0 && iResult == 0) {
					messageEnd.what = 4;

				} else {
					messageEnd.what = 3;

				}

			} else {
				messageEnd.what = 3;
			}
		} catch (Exception e) {
			e.printStackTrace();
			messageEnd.what = 3;
		} finally {
			try {
				if (outputStream != null) {
					outputStream.close();
				}
				if (outputStreamResult != null) {
					outputStreamResult.close();
				}
				processResult.destroy();
				process.destroy();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		handler.sendMessage(messageEnd);
	}

}
